<template>
  <div class="home">
    <div class="flex">
      <h1>网站访问量</h1>
      <span class="primary" @click="jumpPage">查看更多</span>
    </div>
    <div class="header">
      <el-card class="box-card">
        <p class="ft-16">今日</p>
        <p class="ft-30">{{ total.dailyTotal }} <span class="ft-18">次</span></p>
      </el-card>
      <el-card class="box-card">
        <p class="ft-16">本周</p>
        <p class="ft-30">{{ total.weekTotal }} <span class="ft-18">次</span></p>
      </el-card>
      <el-card class="box-card">
        <p class="ft-16">本月</p>
        <p class="ft-30">{{ total.monthTotal }} <span class="ft-18">次</span></p>
      </el-card>
      <el-card class="box-card">
        <p class="ft-16">本年</p>
        <p class="ft-30">{{ total.yearTotal }} <span class="ft-18">次</span></p>
      </el-card>
      <el-card class="box-card">
        <p class="ft-16">总访问量</p>
        <p class="ft-30">{{ total.yearTotal }} <span class="ft-18">次</span></p>
      </el-card>
    </div>
    <div class="chart">
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="解决方案" name="1">
          <span v-if="!xData.length" class="empty">暂无数据</span>
          <div ref="chartA" class="chart-in"></div>
        </el-tab-pane>
        <el-tab-pane label="产品" name="2">
          <span v-if="!xData.length" class="empty">暂无数据</span>
          <div ref="chartB" class="chart-in"></div>
        </el-tab-pane>
        <el-tab-pane label="新闻" name="3">
          <span v-if="!xData.length" class="empty">暂无数据</span>
          <div ref="chartC" class="chart-in"></div>
        </el-tab-pane>
      </el-tabs>
      <div class="type-tab">
        <span
          v-for="(item, index) in types"
          :key="index"
          :class="{ active: activeType === item.value }"
          @click="handleTypeChange(item.value)"
        >
          {{ item.label }}
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import * as api from '@/const/api'

export default {
  title: '首页',
  name: 'Home',
  data() {
    return {
      total: {
        dailyTotal: 0,
        weekTotal: 0,
        monthTotal: 0,
        yearTotal: 0,
      },
      activeName: '1',
      types: [
        {
          value: 1,
          label: '今日',
        },
        {
          value: 2,
          label: '本周',
        },
        {
          value: 3,
          label: '本月',
        },
        {
          value: 4,
          label: '本年',
        },
      ],
      activeType: 1,
      chart: null,
      option: [],
      xData: [],
      yData: [],
    }
  },
  computed: {},
  mounted() {
    this.goPage()
    this.goPageByType(this.activeName, this.activeType)
  },
  methods: {
    async goPage() {
      try {
        const { code, msg, data } = await this.$axios.$get(api.accessRecordStaticsTotal)

        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }

        this.total = data
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    async goPageByType(type, rangeType) {
      try {
        const { code, msg, data } = await this.$axios.$get(api.accessRecordStaticsTypeTotal, {
          params: {
            type,
            rangeType,
          },
        })

        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        this.xData = data.map(({ name }) => {
          const arr = name.split('-')
          arr.shift()
          return arr.join('-')
        })
        this.yData = data.map(({ total }) => total)
        this.drawEcharsTank()
        this.activeName = type
        this.activeType = rangeType
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    handleTabClick(e) {
      this.goPageByType(e.name, this.activeType)
    },
    handleTypeChange(e) {
      this.goPageByType(this.activeName, e)
    },
    // 用echarts 画图
    drawEcharsTank() {
      this.chart && this.chart.dispose()

      this.chart = null

      if (this.activeName === '1') {
        this.chart = echarts.init(this.$refs.chartA)
        this.option = this.handleOptions(this.$refs.chartA)
      } else if (this.activeName === '2') {
        this.chart = echarts.init(this.$refs.chartB)
        this.option = this.handleOptions(this.$refs.chartB)
      } else {
        this.chart = echarts.init(this.$refs.chartC)
        this.option = this.handleOptions(this.$refs.chartC)
      }

      this.chart.setOption(this.option)
    },
    // echarts 图表选项
    handleOptions(chart) {
      const offsetWidth = chart.offsetWidth
      const xData = this.xData
      const fontsize = 12
      let barWidth = offsetWidth / xData.length
      const wordNum = parseInt(barWidth / fontsize)

      this.chartWidth = offsetWidth
      if (barWidth > 20) {
        barWidth = 20
      }

      const option = {
        backgroundColor: 'rgba(0,0,0,0)',
        grid: {
          top: '12%',
          left: '3%',
          right: '3%',
          bottom: '6%',
          containLabel: true,
        },

        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 1)', // 设置背景颜色
          textStyle: {
            color: '#666',
          },
          borderWidth: 1,
          borderColor: 'rgba(0, 117, 255, 0)',
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              color: 'rgba(0, 11, 34, .1)',
            },
          },
          formatter(params) {
            let res = ''
            for (let i = 0; i < params.length; i++) {
              /* eslint-disable */
              let color =
                typeof params[i].color === 'string'
                  ? params[i].color
                  : params[i].color.colorStops
                  ? params[i].color.colorStops[0].color
                  : ''
              /* eslint-enable */
              res +=
                "<div style='margin-bottom:5px;padding:0 3px;width:100%;height:20px;line-height:20px;border-radius:3px;font-size: 13px;'><p>" +
                params[i].axisValueLabel +
                '</p></div>'
              res += `<div style="color: #333;font-size: 13px; padding:12px 12px;line-height: 20px">
                    <span style="display:inline-block;margin-right:5px;border-radius:2px;width:10px;height:10px;background-color:${[
                      color,
                    ]};"></span>
                    访问量<span style="float:right">${params[i].data}</span>
                  </div>`
            }
            return res
          },
        },
        xAxis: {
          data: this.xData,
          axisLine: {
            show: true,
            lineStyle: {
              color: '#eeeeee',
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: 'rgba(153, 155, 158, 1)',
            fontSize: 12,
            interval: 0,
            formatter(value, index) {
              const strs = value.split('')
              let str = ''
              /* eslint-disable */
              for (let i = 0, s; (s = strs[i++]); ) {
                /* eslint-enable */
                str += s
                if (!(i % wordNum)) {
                  str += '\n'
                }
              }
              return str
            },
          },
        },
        yAxis: [
          {
            type: 'value',
            axisLine: {
              show: true,
              lineStyle: {
                color: 'rgba(0,0,0,0)',
              },
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: 'rgba(187, 187, 187, 1)',
              fontSize: 12,
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: 'rgba(0,0,0,0)',
              },
            },
          },
        ],
        series: [
          {
            name: '库存量',
            type: 'bar',
            barWidth,
            barMaxWidth: 23,
            zlevel: 2,
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: 'rgba(61, 139, 247, 1)',
                    },
                    {
                      offset: 1,
                      color: 'rgba(61, 139, 247, 0.7)',
                    },
                  ],
                  false
                ),
              },
            },
            label: {
              normal: {
                show: false,
                fontSize: 13,
                color: 'rgba(187, 187, 187, 1)',
                position: 'top',
              },
            },
            data: this.yData,
          },
        ],
      }

      return option
    },
    jumpPage() {
      this.$router.push({
        path: '/record-list',
      })
    },
  },
}
</script>

<style lang="less" scoped>
.home {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  padding: 10px;
  display: flex;
  flex-direction: column;

  .flex {
    display: flex;
    justify-content: space-between;
    padding: 5px 0 10px 0;

    h1 {
      font-size: 18px;
    }

    .primary {
      cursor: pointer;
      color: #409eff;
      font-weight: bold;
    }
  }

  .header {
    display: flex;

    .box-card {
      flex: 1;

      + .box-card {
        margin-left: 20px;
      }
    }

    .ft-16 {
      font-size: 16px;
      color: #666;
    }

    .ft-30 {
      font-size: 30px;
      color: #333;
      font-weight: 500;
      line-height: 60px;

      .ft-18 {
        font-size: 18px;
      }
    }
  }

  .chart {
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;
    flex: 1;
    position: relative;
    overflow: hidden;

    :deep(.el-tabs) {
      height: 100%;
      display: flex;
      flex-direction: column;

      .el-tabs__nav {
        margin-left: 20px;
      }

      .el-tabs__item {
        height: 56px;
        line-height: 56px;
      }

      .el-tabs__content {
        flex: 1;
      }

      .el-tab-pane {
        height: 100%;
      }
    }

    .chart-in {
      width: 100%;
      height: 100%;
    }

    .empty {
      padding-left: 20px;
    }
  }

  .type-tab {
    position: absolute;
    top: 20px;
    z-index: 20;
    right: 40px;

    span {
      cursor: pointer;
      margin-left: 15px;

      &.active {
        color: #409eff;
        font-weight: bold;
      }
    }
  }
}
</style>
